package com.gitee.feizns.webtemplate.commons.data.order;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author feizns
 * @since 2019/5/12 0012
 */
public class OrderUtils {

    private OrderUtils() {}

    public static String getOrderByStrForSql(List<OrderColumn> orderColumns) {
        StringBuilder buildSql = new StringBuilder();
        if ( orderColumns != null && orderColumns.isEmpty() == false ) {
            buildSql.append(" ORDER BY ");

            //如果所有的排序规则都一样。（只是为了看着舒服.）
            boolean allMatchAsc = orderColumns.stream().allMatch(item -> item.getOrder() == Order.asc);
            boolean allMatchDesc = orderColumns.stream().allMatch(item -> item.getOrder() == Order.desc);
            if ( allMatchAsc || allMatchDesc ) {
                Order order = allMatchAsc ? Order.asc : Order.desc;
                return buildSql.append(
                        orderColumns.stream()
                                .map(OrderColumn::getColumnName)
                                .collect(Collectors.joining(", "))
                ).append(String.format(" %s ", order.name().toUpperCase())).toString();
            }

            return buildSql.append(
                    orderColumns.stream()
                            .map(item -> item.getColumnName() + " " + item.getOrder().name().toUpperCase())
                            .collect(Collectors.joining(", "))
            ).toString();
        }
        return buildSql.toString();
    }

}
